import { RouteRecordRaw } from 'vue-router';
import { defineStore } from 'pinia';
import { constantRoutes } from '@/router';
import { store } from '@/store';
import { listRoutes } from '@/framework/api/menu';
import { AppRoutesData } from '@/framework/api/menu/types';
import { isExternal } from '@/utils/validate';
import { upperCamelCase } from '@/framework/utils/index';
import { ref } from 'vue';

const modules = {...import.meta.glob('@/views/**/**.vue'),...import.meta.glob('@/framework/views/**/**.vue')};
export const Layout = () => import('@/framework/layout/index.vue');

//该方法被弃用  默认有所有权限  返回值 永久为true
const hasPermission = (roles: string[], route: RouteRecordRaw) => {
  if (route.meta && route.meta.roles) {
    if (roles.includes('ROOT')) {
      return true;
    }
    return roles.some(role => {
      if (route.meta?.roles !== undefined) {
        return (route.meta.roles as string[]).includes(role);
      }
    });
  }
  return true; //返回值 永久为true
};

const dealComponentPath = (component:string) => {
  if(!component) return '' 
  if(component.indexOf('.vue') > -1) {
    return component 
  }else{
    return component + '.vue'
  }
  
}
const filterAsyncRoutes = (routes: RouteRecordRaw[], roles: string[]) => {
  const res: RouteRecordRaw[] = [];
  
  routes.forEach(route => {
    const tmp = { ...route } as any;
    if (hasPermission(roles, tmp)) {
      if (tmp.component == 'layout') {
        tmp.component = Layout;
      } else {
        const component = modules[`/src/${dealComponentPath(tmp.component)}`] as any;
        if (component) {
          tmp.component = component;
        } else {
          tmp.component = modules[`/src/views/error-page/404.vue`];
        }
      }
      res.push(tmp);

      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles);
      }
    }
  });
  return res;
};

// setup
export const usePermissionStore = defineStore('permission', () => {
  // state
  const routes = ref<RouteRecordRaw[]>([]);
  const addRoutes = ref<RouteRecordRaw[]>([]);
  const appRoutes = ref<AppRoutesData[]>([]);

  // actions
  function setRoutes(newRoutes: RouteRecordRaw[]) {
    addRoutes.value = newRoutes;
    routes.value = constantRoutes.concat(newRoutes);
  }

  function setAppRoutes(newAppRoutes: AppRoutesData[]){
    appRoutes.value = newAppRoutes;
  }

  function generateRoutes(roles: string[]) {
    return new Promise<RouteRecordRaw[]>((resolve, reject) => {
      listRoutes()
        .then(response => { 
          const data = response.data;  //后端返回数据
          const loadMenuData:any[] = [] //后端返回数据
          const asyncRoutes:RouteRecordRaw[] = []  //vue 路由数据
          const appRoutes:AppRoutesData[] = []  //前端存储数据
          Object.assign(loadMenuData, data)
          generAppMenu(asyncRoutes, loadMenuData, appRoutes)
          const accessedRoutes = filterAsyncRoutes(asyncRoutes, roles);
          console.log('bbb',accessedRoutes)
          // const accessedRoutes = filterAsyncRoutes(data, roles);
          setAppRoutes(appRoutes);
          setRoutes(accessedRoutes);
          resolve(accessedRoutes);
        })
        .catch(error => {
          reject(error);
        });
    });
  }
  return { routes, appRoutes, setRoutes, generateRoutes };
});

// 非setup
export function usePermissionStoreHook() {
  return usePermissionStore(store);
}

function generAppMenu(routes:RouteRecordRaw[], data:any[], appRoutes:AppRoutesData[]) {
  for (const item of data) { // 遍历应用
    const appRoute:RouteRecordRaw[] = []
    if (item.children) {
      generaMenu(appRoute, item.children, {
        meta: {
          title: item.title
        },
        path: item.path
      }) // 生成当前应用的路由菜单
    }
    for (const app of appRoute) {
      routes.push(app)
    }
    appRoutes.push({
      path: item.path,
      name: item.title,
      hidden: item.visible == 'N',
      icon: item.icon,
      children: appRoute,
      meta: { title: item.title, icon: item.icon, hidden: item.visible == 'N' }
    })
  }
}
function generaMenu(routes:RouteRecordRaw[], data:any[], parentTitle?:any) {
  // 分应用路由
  if (data != null) {
    // 遍历后台返回的菜单路由
    data.forEach(item => {
      let menu:any = {}
      // 内链地址
      if (item.component && (item.component.startsWith('/') || isExternal(item.component))) {
        menu = {
          path: item.path,
          // component: IframePageView,
          component: null,
          name: upperCamelCase(item.menuCode),
          meta: { title: item.title, icon: item.icon, parentTitle: parentTitle },
          hidden: item.visible == 'N',
          props: {
            url: item.component,
            id: item.path
          }
        }
      } else if (item.path && isExternal(item.path)) { // 外链地址
        menu = {
          path: item.path,
          hidden: item.visible == 'N',
          meta: { title: item.title, icon: item.icon }
        }
      } else { // 组件
        const temp = {
          path: item.path,
          // component: item.component ? (resolve) => require([`@/${item.component === 'layout' ? 'framework/layout' : item.component}`], resolve) : AppView, // 需要让后台处理layout
          component: item.component ,
          name: upperCamelCase(item.menuCode),
          meta: { title: item.title, icon: item.icon, parentTitle: parentTitle, noCache: false, hidden: item.visible == 'N' },
          hidden: item.visible == 'N',
          menuType: item.menuType,
          children: []
        }
        menu = parentTitle && !item.children ? {
          menuType: 'layout', // 默认
          path: '/selfLayout',
          // component: (resolve) => require([`@/framework/layout`], resolve),
          component: 'layout',
          children: [temp]
        } : temp
        // menu = temp
      }

      if (item.children) {
        generaMenu(menu.children, item.children)
      }
      if (!routes) {
        routes = []
      }
      routes.push(menu)
    })
  }
}